package Q438;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 找到字符串中所有的字母异位词
 * @author 23737
 * @time 2021.11.28
 */
public class Test {
    public static void main(String[] args) {
        List<Integer> anagrams = new Solution().findAnagrams("cbaebabacd", "abc");
        Iterator<Integer> iterator = anagrams.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

/**
 * 暴力解法
 */
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        if (s.length() == 0 || p.length() == 0){
            return result;
        }
        for (int i = 0; i < s.length(); i++) {
            if(p.length()+i > s.length()){
                break;
            }
            String checkStr = s.substring(i,p.length()+i);
            if(checkFun(checkStr,p)){
                result.add(i);
            }
        }
        return result;
    }

    /**
     * 判断是否是字母异位字符串
     * @param checkStr
     * @param p
     */
    private boolean checkFun(String checkStr, String p) {
        char[] chars = checkStr.toCharArray();
        char[] chars1 = p.toCharArray();

        int[] result = new int[26];

        for (char aChar : chars) {
            result[aChar-'a'] += 1;
        }

        for (char c : chars1) {
            result[c-'a'] -= 1;
        }

        for (int i : result) {
            if (i != 0){
                return false;
            }
        }
        return true;
    }
}